<?php

class jsc {

    public static function get_data($yumingid) {
        $data = self::get_data_cache($yumingid);
        if (empty($data)) {
            $template = "/jsctpl/jsc1";
            $dd = self::get_title_and_content(); //从采集缓存中拿数据
            if (!empty($dd)) {
                $content = $dd['content'];
                $content = str_replace(array("<p>(点击图片看大图)</p>", "显示全文"), "", $content);
                //过滤原标题
                $content = str_replace("原标题：", "", $content);
                $content = preg_replace("/20\d{2}-\d{2}-\d{2} \d{2}:\d{2}/i", "", $content);
                $content = str_replace("</p></p>", "</p>", $content);
                $content = str_replace("<p><p align=\"center\">", "<p align=\"center\">", $content);
                $content = preg_replace("/<a[^>]*>(.*?)<\/a>/is", "$1", $content); //去除A标签
                $content= preg_replace('/<\s*img\s+[^>]*?src\s*=\s*(\'|\")(.*?)\\1[^>]*?\/?\s*>/i', '', $content);//去除IMG标签
                $content= preg_replace('/<script[\s\S]*?<\/script>/i', '', $content);//去除script标签
                $content = preg_replace("/上一页.*?下一页/", "", $content);
                $content =  str_ireplace('</p>','qiushuifengge',$content);
                $content =  str_ireplace('</div>','qiushuifengge',$content);
                $content = preg_replace("/<br[^>]*>/is", 'qiushuifengge', $content);
                $content = strip_tags($content);
                $content_arr = explode('qiushuifengge',$content);
                $content = self::content_new_template($content_arr);
                
                $title = $dd['title'];
                $data = self::get_seo_data($title, $content, $yumingid);
                $keyword = $data['seo_keyword'];
                $des = $data['seo_desc'];
            } else {
                $content = self::read_content();
                $keys = self::read_keys();
                $title = duqu($keys, 1);
                $title = $title[0];
                $content = duqu($content, 40);
                $content = self::content_template($content);
                $data = self::get_seo_data($title, $content, $yumingid);
                if (!empty($data)) {
                    $title = $data['title'];
                    $content = $data['content'];
                    $keyword = $data['seo_keyword'];
                    $des = $data['seo_desc'];
                } else {
                    $keyword = duqu($keys, 8);
                    $keyword = implode(',', $keyword);
                    $des = duqu($keys, 12);
                    $des = implode(',', $des);
                }
            }
            self::set_data_cache($yumingid, [
                'title' => $title,
                'keywords' => $keyword,
                'des' => $des,
                'template' => $template,
                'content' => $content
            ]);
            set_url_cache($yumingid); //写入URL日志
        } else {
            $keys = self::read_keys();
            $title = $data['title'];
            $keyword = $data['keywords'];
            $des = $data['des'];
            $content = $data['content'];
            $template = $data['template'];
        }
        //$keyword1 = duqu($keys, 50);
        //$keyword2 = duqu($keys, 8);
        //$keyword3 = duqu($keys, rand(5, 10));
        
        $rand_t_arr = self::get_rand_caiji_cache();
        $keyword1 = $rand_t_arr['keyword1'];
        $keyword2 = $rand_t_arr['keyword2'];
        $keyword3 = $rand_t_arr['keyword3'];
        $res = array(
            'title' => $title,
            'keyword' => $keyword,
            'des' => $des,
            'content' => $content,
            'template' => $template,
            'keyword1' => $keyword1,
            'keyword2' => $keyword2,
            'keyword3' => $keyword3,
        );
        return $res;
    }

    //获取关键字优化后的内容
    protected static function get_seo_data($title, $content, $yumingid) {
        $seod['title'] = $title;
        $seod['body'] = $content;
        $arr_words = yumi::get_words_lists(10, $yumingid);
        $seod = yumi::seoword($seod, $yumingid, $arr_words);
        if (empty($seod)) {
            return false;
        }
        $title = $seod['title'];
        $keywords_tags = yumi::autokeywords($seod, $yumingid, $arr_words);
        if (empty($keywords_tags)) {
            return false;
        }
        $seo_keyword = $keywords_tags['keyword'];
        $title = strip_tags($title);
        $title = addslashes($title);
        $seo_keyword = addslashes($seo_keyword);
        $seo_desc = addslashes($keywords_tags['keyword']);
        $content = $seod['body'];
        $content = yuminew::replace_word($content, $yumingid);
        return ['title' => $title, 'seo_keyword' => $seo_keyword, 'seo_desc' => $seo_desc, 'content' => $content];
    }

    //得到缓存数据
    protected static function get_data_cache($yumingid) {
        $files = get_jsccache_path($yumingid);
        if (is_file($files)) {
            $data = file_get_contents($files);
            $data = json_decode($data, true);
            return $data;
        }
        return false;
    }

    //写入缓存数据
    protected static function set_data_cache($yumingid, $cache) {
        $files = get_jsccache_path($yumingid);
        if (!is_file($files)) {
            $pathinfo = pathinfo($files);
            mkdirs($pathinfo['dirname']);
            file_put_contents($files, json_encode($cache));
        }
    }

    protected static function read_content() {
        $path = ROOT . DS . 'jscdata' . DS . 'contents';
        $path_list = jsc::get_content_dir();
        if (!empty($path_list)) {
            $file_key = array_rand($path_list, 1);
            return $path . DS . $path_list[$file_key];
        } else {
            return false;
        }
        //return $path . DS . '1.txt';
    }

    protected static function read_keys() {
        $path = ROOT . DS . 'jscdata' . DS . 'keys';
        $path_list = jsc::get_title_dir();
        if (!empty($path_list)) {
            $file_key = array_rand($path_list, 1);
            return $path . DS . $path_list[$file_key];
        } else {
            return false;
        }
    }

    protected static function read_lian() {
        $path = ROOT . DS . 'jscdata' . DS . 'lunlian';
        return $path . DS . '1.txt';
    }

    protected static function content_template($xiaoshuo) {
        $temp = "<p>{juzi} {juzi}{juzi} {juzi}{juzi} {juzi}{juzi} {juzi}{juzi} {juzi}</p><p>{juzi} {juzi}{juzi} {juzi}{juzi} {juzi}{juzi} {juzi}{juzi} {juzi}{juzi}</p><p>{juzi} {juzi}{juzi} {juzi}{juzi} {juzi}{juzi} {juzi}</p><p>{juzi} {juzi}{juzi} {juzi}{juzi} {juzi}{juzi} {juzi}</p>";
        foreach ($xiaoshuo as $key => $v) {
            $temp = preg_replace('/\\{juzi\\}/', UnicodeEncode($v), $temp, 1);
        }
        return $temp;
    }
    
    protected static function content_new_template($content) {
        $text = '';
        foreach($content as $key=>$v) {
            if(!empty(trim($v))) {
                $text.='<p>'.UnicodeEncode(trim($v)).'</p>';
            }
        }
        return $text;
    }

    


    //得到当天所有站点的寄生虫推送量
    public static function count_today_push() {
        $total = 0;
        $data = mredis::zRangeByScore('baidupush', '-inf', '+inf', ['withscores' => TRUE, limit => array(0, -1)]);
        foreach ($data as $key => $v) {
            $total += (5000000 - $v);
        }
        $total = intval($total);
        return ['total' => $total, 'lists' => $data];
    }

    //得到寄生虫标题库目录
    public static function get_title_dir() {
        $path = ROOT . '/jscdata/keys';
        $data = printdir($path);
        return $data;
    }

    //得到寄生虫源数据库目录
    public static function get_content_dir() {
        $path = ROOT . '/jscdata/contents';
        $data = printdir($path);
        return $data;
    }

    //随机从文章表中抽出一篇文章
    public static function get_title_and_content($yumingid = null) {
        $table = 'caiji_cache';
        $article = db::find("SELECT * FROM `{$table}` AS t1 JOIN (SELECT ROUND(RAND() * (
            (SELECT MAX(id) FROM `{$table}`)-(SELECT MIN(id) FROM `{$table}`))+(SELECT MIN(id) FROM `{$table}`)) AS id) AS t2
            WHERE t1.id >= t2.id
            ORDER BY t1.id LIMIT 1;"
        );
        if (!empty($article)) {
            preg_match_all('|<p>(.*?)<\/p>|s', $article['content'], $match);
            if (!empty($match[0]) && is_array($match[0]) && count($match[0]) > 3) {
                $arr = $match[0];
                $tmp_arr = $arr;
                $count = count($arr) >= 6 ? 6 : count($arr);
                for ($i = 1; $i <= $count - 1; $i++) {
                    $key1 = rand(1, (count($arr) - 1));
                    $arr1 = $arr[$key1];
                    $key2 = rand(1, (count($arr) - 1));
                    $arr2 = $arr[$key2];
                    $article['content'] = str_change($article['content'], $arr1, $arr2);
                }
                $bd = getBDinsertArr(mb_strlen($article['content']));
                $article['content'] = randomInsert($article['content'], $bd);
            }
            if (!empty($article['content'])) {
                $bd = getBDinsertArr(mb_strlen($article['content']));
                $article['content'] = randomInsert($article['content'], $bd);
            }
        }
        return $article;
    }

    //把采集的数据写缓存表
    public static function write_caiji_cache($data) {
        $data['status'] = 2;
        $data['updatetime'] = time();
        pdodb::insert('caiji_cache', $data);
    }
    
    
    //随机获取推荐数据
    public static function get_rand_caiji_cache() {
        $table = 'caiji_cache';
        $article = db::select("SELECT * FROM `{$table}` WHERE id >= (SELECT floor(RAND() * (SELECT MAX(id) FROM `{$table}`))) ORDER BY id LIMIT 200");
        $keyword1 = [];
        $keyword2 =[];
        $keyword3 = [];
        for($i=0;$i<50;$i++) {
            $rk = array_rand($article);
            $keyword1[] = $article[$rk]['title'];
        }
        for($i=0;$i<8;$i++) {
            $rk = array_rand($article);
            $keyword2[] = $article[$rk]['title'];
        }
        $ran_count = rand(5,10);
        for($i=0;$i<$ran_count;$i++) {
            $rk = array_rand($article);
            $keyword3[] = $article[$rk]['title'];
        }
        return ['keyword1'=>$keyword1,'keyword2'=>$keyword2,'keyword3'=>$keyword3];
    }

}
